package com.hqyj.demo.controller;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.hqyj.demo.entity.Admin;
import com.hqyj.demo.entity.vo.LoginParams;
import com.hqyj.demo.utils.CacheConstantsKey;
import com.hqyj.demo.utils.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @PostMapping("/login_erp")
    public R login_erp(@RequestBody LoginParams loginParams, HttpServletRequest request) {
        //判断验证码
        Object code = request.getSession().getAttribute(CacheConstantsKey.CAPTCHA_CODE_KEY);
        if (code==null){
            return R.error().message("验证码为空");
        }
        if (!String.valueOf(code).equals(loginParams.getCode())){
            return R.error().message("验证码错误、请重新输入！");
        }

        SecurityUtils.getSubject().getSession().setTimeout(-1000L);

        //获取当前subject
        Subject subject = SecurityUtils.getSubject();
        //创建token
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginParams.getUsername(), loginParams.getPassword());
        //认证
        try {
            subject.login(usernamePasswordToken);
            //存入数据
            Admin admin = (Admin) SecurityUtils.getSubject().getSession().getAttribute(CacheConstantsKey.LOGIN_TOKEN_KEY);
            //System.out.println(admin+"=========================================================");
            return R.ok().message("登录成功").data("adminObj", admin);
        } catch (Exception e) {
            return R.error().message("用户名或密码错误");
        }
    }
    //生成验证码
    @GetMapping("/captchaCode")
    public void captchaCode(HttpServletResponse response) {
        //生成验证码
        String text = defaultKaptcha.createText();

        System.out.printf("验证码:" + text);

        //存储到session中
        SecurityUtils.getSubject ().getSession ().setAttribute (CacheConstantsKey.CAPTCHA_CODE_KEY,text);

        BufferedImage image = defaultKaptcha.createImage(text);
        try {
            //输出流输出验证码
            ImageIO.write(image, "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}
